package com.txc.common.utils.pay;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

/**
 * @ClassName: QrCodeUtil
 * @Description: 公共工具类
 * @Author: TXC
 * @Date: 2023-12-25 17:47
 **/
public class CommonUtil {
    static final String FORMAT = "png";
    static final int width = 256;
    static final int height = 256;

    /**
     * 生成二维码
     *
     * @param qrCode  二维码
     * @param imgPath 文件地址
     */
    public static void createQRCodeImage(String qrCode, String imgPath) {
        HashMap<EncodeHintType, Object> hashMap = new HashMap<>();
        hashMap.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        hashMap.put(EncodeHintType.MARGIN, 2);
        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(qrCode, BarcodeFormat.QR_CODE, width, height, hashMap);
            MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, new File(imgPath).toPath());
        } catch (IOException | WriterException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * multiFile转File
     *
     * @param multiFile multiFile文件
     * @return File文件
     */
    public static File multipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf(".")) + System.currentTimeMillis();
        String prefix = fileName.substring(0, fileName.lastIndexOf("."));
        // 若要防止生成的临时文件重复,需要在文件名后添加随机码
        try {
            File file = File.createTempFile(prefix, suffix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            System.out.println("MultipartFile转File失败：" + e);
        }
        return null;
    }

    public static List<File> getUploadDirectory() throws FileNotFoundException {
        // 开发环境获取 target/classes 目录：清理重新编译后就没有了
        File targetPath = new File(ResourceUtils.getURL("classpath:").getPath());
        // 生产环境 不存在 target/classes 目录
        if (!targetPath.exists()) {
            // 获取当前运行目录
            targetPath = new File("");
        }
        // 开发环境 resources 目录：可永久保存
        String resourcesPath = System.getProperty("user.dir") + "/upms-pay/src/main/resources";
        File path = new File(resourcesPath);
        File upload = new File(path.getAbsolutePath(), "upload");
        File uploadTarget = new File(targetPath.getAbsolutePath(), "upload");
        // 不存在则创建
        if (!upload.exists()) {
            upload.mkdirs();
        }
        if (!uploadTarget.exists()) {
            uploadTarget.mkdirs();
        }
        List<File> files = new ArrayList<File>();
        files.add(upload);
        files.add(uploadTarget);
        return files;
    }

    public static String upload(MultipartFile myFile) {
        String filePath = "";
        if (!myFile.isEmpty()) {
            try {
                String filename = myFile.getOriginalFilename();
                filename = UUID.randomUUID() + filename.substring(filename.lastIndexOf("."));
                List<File> files = getUploadDirectory();
                File curFile = new File(files.get(0), filename);
                myFile.transferTo(curFile);
                FileCopyUtils.copy(curFile, new File(files.get(1), filename));
                filePath = curFile.getAbsolutePath();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return filePath;
    }

    public static String getStrByBody(Map<String, Object> body, String name) {
        if(body == null) {
            return null;
        }
        Object object = body.get(name);
        if (object == null) {
            return null;
        }
        return object.toString().replace("\"", "");
    }

}
